package com.sxt.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.sxt.entity.User;
import com.sxt.param.WxLoginParam;
import com.sxt.service.UserService;

import io.swagger.annotations.ApiOperation;

@RestController
public class LoginController {

	@Autowired
	private UserService userService ;

	@GetMapping("/login")
	public ResponseEntity<String> toLogin(){
		return ResponseEntity.badRequest().body("你没有登录,或登录过期,请重新登录");
	}
	/**
	 * 怎么利用shiro 登录
	 * @param loginParam
	 * @return
	 */
	@PostMapping("/login")
	public ResponseEntity<Object> login(@RequestBody WxLoginParam loginParam){
		UsernamePasswordToken token = new UsernamePasswordToken(loginParam.getPrincipal(), "WX");
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			String accessToken =  subject.getSession().getId().toString();
			User user = (User)subject.getPrincipal();
			Map<String, Object> result = new HashMap<String,Object>();
			result.put("nickName", user.getNickName()); // 新增的用户没有该值
			result.put("userStutas", user.getStatus()); // 新增的用户默认启用
			result.put("access_token", accessToken);
			return ResponseEntity.ok(result);
		} catch (AuthenticationException e) {
			return ResponseEntity.badRequest().body(e.getMessage());
		}
	}

	@ApiOperation("修改用户的数据")
	@PutMapping("/p/user/setUserInfo")
	public ResponseEntity<Void> updateUserInfo(@RequestBody User user){
		User current = (User)SecurityUtils.getSubject().getPrincipal(); // 当前访问该接口的用户
		user.setUserId(current.getUserId());
		userService.updateById(user); // 性别要处理,用户的昵称要处理(因为有的用户的昵称比较骚(标签),所有需要处理)
		return ResponseEntity.ok().build();

	}
}
